#
# "@(#) $Id: App.py,
#
# This work is released under the GNU GPL, version 2 or later.
#
from UI.MainWindow import *
from UI.TrayToolTip import *
from UI.RatingMenu import *
from Player import *

from DB.Library import *
from DB.CDLibrary import *
from DB.RadioLibrary import *
from DB.EncoderLibrary import *
import DB.PLS

from Utils.kdeemul import *
from Utils import Settings 
from Utils.Paths import *
from Utils.utils import *

from FileBasedPlayer import *

from CD.CDROM import *
from CD.Burner import *
from CD.Importer import *
from CD.Ripper import *

#import gc

_theApplication = None
_theMainApplication = False
#gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_UNCOLLECTABLE)

class App(KUniqueApplication):
	def __init__(self,version):
		self.window = None
		self.version = version
		global _theApplication,_theMainApplication
		_theApplication = self
		self.args = None
		self.shouldPlayAfterImport = False
		KUniqueApplication.__init__(self,True,True,False)
		#QObject.connect(self,SIGNAL("saveYourself()"),self.saveStuff)
	
	def makeWindow(self,splash = None):
		self.initStuff(splash)
		QObject.connect(self,SIGNAL("lastWindowClosed()"),self.saveStuff)
		try:
			QObject.connect(self,SIGNAL("aboutToQuit()"),self.saveStuff)
		except: pass
		if splash:
			splash.message(i18n("Reading settings..."))
			self.processEvents()
		self.settings = Settings.settings()
		if splash:
			splash.message(i18n("Building interface..."))
			self.processEvents()
		
		self.window = MainWindow(self.version,self)
		self.window.app = self
		p = eval(self.settings.get("Main Window Position",'[100,100,800,500]'))
		if len(p)!=4:
			p = [100,100,800,500]
		self.window.setGeometry(p[0],p[1],p[2],p[3])
		self.setMainWidget(self.window)
		self.window.show()
		self.buildSystemTray()
		self.saved = False
		if self.args:
			self.processArgs()
		_theMainApplication = True
		return self.window
	
	def newInstance(self):
		global _theApplication,_theMainApplication
		if self.window:
			self.window.show()
		args = KCmdLineArgs.parsedArgs()
		if args:
			if args.count()>0:
				self.args = args
			if args.isSet("suspend"):
				Player.killCurrentPlayer()
			if args.isSet("play"):
				self.shouldPlayAfterImport = True
			settings = Settings.settings()
			settings['isMP3Beamer'] = args.isSet('mp3beamer')
			if _theMainApplication and self.args:
				self.processArgs()
		return 0
	
	def processArgs(self):
		fileNames = []
		argsCount = 0
		#print "entering process args loop"
		while argsCount<self.args.count():
			url = self.args.url(argsCount)
			#print "url %s" % url
			protocol = str(url.protocol())
			#print "protocol",protocol
			if protocol=='file':
				path = unikode(url.path())
				if os.path.isdir(path):
					fileNames.append(path.encode('latin-1'))
				else:
					(root,extension) = os.path.splitext(path)
					#print "got extension",extension
					if extension=='.pls':
						#print "got pls file!"
						streams = PLS.readAndParsePLS(path)
						#print "streams",streams
						if streams:
							url = KURL(streams[0])
							protocol = str(url.protocol())
					else:
						fileNames.append(path.encode('latin-1'))
						#print "appended file"
			if protocol=='http':
				track = RadioTrack()
				track.title = "Lsongs"
				track.location = str(url.url())
				track.isStream = True
				print "App.processArgs: streaming",track.location
				Player.singleton().playTrack(track)
				break
			argsCount += 1
		#print "leaving process args loop"
		if len(fileNames)>0:
			print "fileNames",fileNames
			library = Library.mainLibrary()
			library.importFiles(fileNames,None,self.shouldPlayAfterImport)
		self.shouldPlayAfterImport = False
	
	def initStuff(self,splash = None):
		if splash:
			splash.message(i18n("Initializing audio...."))
			self.processEvents()
		if splash:
			splash.message(i18n("Initializing CD devices..."))
			self.processEvents()
		CDROMS.singleton().burnerInfo()

	def saveStuff(self):
		if not self.saved:
			try: Player.killCurrentPlayer()
			except: pass
			#print "saving Library"
			lib = Library.mainLibrary()
			lib.dirty = False
			lib.writePickleFile()
			#lib.writeBinaryFile()
			lib.writeXMLFile()
			RadioLibrary.singleton().writeXMLFile()
			EncoderLibrary.singleton().writeXMLFile()
			Settings.singleton().writeXMLFile()
			print "App.saveStuff: killing threads"
			try: Burner.killCurrentBurner()
			except: pass
			try: Ripper.killCurrentRipper()
			except: pass
			try: Encoder.killCurrentEncoder()
			except: pass
			try: Importer.killCurrentImporter()
			except: pass
			#CD.CDMounter.killCurrentCDMounter()
			try: CDLibraries.singleton().killTasks()
			except: pass
			try: Player.killAll()
			except: pass
			self.saved = True

	def buildSystemTray(self):
		try:
			self.tray = KSystemTray(self.window)
			self.tray.setPixmap(QPixmap(art("8trak_taskbar.png")))
			menu = self.tray.contextMenu()
			self.window.playAction.plug(menu)
			self.window.pauseAction.plug(menu)
			self.window.nextSongAction.plug(menu)
			self.window.previousSongAction.plug(menu)
			self.trayTip = TrayToolTip(self.tray)
			QObject.connect(self.tray,SIGNAL("quitSelected()"),self.trayQuit)
			self.tray.show()
		except: pass

	def trayQuit(self):
		self.saveStuff()
		self.quit()
			
	def static_singleton():
		global _theApplication
		return _theApplication
	singleton = staticmethod(static_singleton)
